<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\ResponseException;
use App\Models\Goods;
use App\Models\GoodsCategory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
	public function categorys()
    {
    	//首页的所有一级分类
		$categorys = GoodsCategory::query()
					->select('id','category_name as text')
					->where([
						'is_show'=>1,
						'pid'=>0,
					])
					->orderBy('sort','desc')
					->get()->toArray();

//		//第一个一级分类下的所有子分类
//		$topChildId = $categorys['0']['id'];
//
//		$childCategoryIds = getChildIds('goods_category',$topChildId);
//
//		$childCategorys = [];
//		$goodsList = [];
//
//		if($childCategoryIds){
//			$childCategorys = GoodsCategory::query()
//							->select('id','category_name')
//							->where('pid',$topChildId)
//							->orderBy('sort','desc')
//							->get()->toArray();
//
//
//		}

		$data = [
			'categorys'=>$categorys,
//			'child_categorys'=>$childCategorys,
//			'goods_list'=>$goodsList,
		];
		throw new ResponseException(200,'ok',$data);
    }


    /**
     * 获得商品子分类
     * User: Clannad ~ ☆
     * DataTime：2020/1/14 21:35
     */
    public function getChildCategory()
    {
        $id = request()->input('id');

        if(!$id){
            throw new ResponseException(404,'分类不存在');
        }

        //获得分类下子分类
        $childrenIds = getChildIds('goods_category',$id,['is_show'=>1]);

        $childCategory = GoodsCategory::query()
                        ->select('id','category_name')
                        ->whereIn('id',$childrenIds)
                        ->where([
                            'is_show'=>1
                        ])->get()->toArray();

        throw new ResponseException(200,'ok',$childCategory);
    }

	/**
	 * 获得分类下的商品
	 * User: Clannad ~ ☆
	 * DataTime：2020/1/9 0009 20:53
	 */
	public function goods(Request $request)
    {
    	if(!$category_id = $request->input('category_id')){
    	    throw new ResponseException(400,'缺少分类参数');
    	}

		$sort = 'created_at';
    	$order_by = 'desc';

		if($request->input('sort')){
			$sort = $request->input('sort');
		}

		if($request->input('order_by')){
			$order_by = $request->input('order_by');
		}

		$category = GoodsCategory::query()
					->select('id','pid')
					->where([
						'is_show'=>1,
						'id'=>$category_id
					])
					->first()->toArray();

		if($category['pid'] == 0){ //顶级分类 需要获取小分类
			$childCategoryIds = getChildIds('goods_category',$category_id);
		}else{
			$childCategoryIds[] = $category_id;
		}

		//当前分类下的所有商品
		$goods = Goods::query()
			->select('id','goods_name','price','thumb','created_at')
			->whereIn('category_id',$childCategoryIds)
			->where(['status'=>1])
			->orderBy($sort,$order_by)
			->paginate(8);

		throw new ResponseException(200,'ok',$goods);
    }
}
